﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;

namespace Genuilder.Extensibility.Tests
{
	[TestClass]
	public class DependenciesTest
	{
		[TestMethod]
		public void TargetFileShouldBeCreated()
		{
			var mockRepo = new MockCodeItemMementoRepository();
			var repository = new DirectoryCodeRepository(mockRepo);
			var fileName = Helper.CreateFile("TargetFileShouldBeCreated");
			var generatedFileName = "TargetFileShouldBeCreated.Gen";
			mockRepo.SaveCodeItemMementos(new List<Genuilder.Extensibility.DirectoryCodeRepository.CodeItemMemento>()
			{
				new Genuilder.Extensibility.DirectoryCodeRepository.CodeItemMemento()
				{
					FileName = fileName,
					LastModified = DateTime.Now
				},
			});
			repository.Files.Add(fileName);



			bool shouldUpdate = false;

			repository.CodeItemCreated += (s, a) =>
			{
				if(a.Name == fileName)
				{
					var dep = a.SourceOf(generatedFileName);
					dep.ShouldUpdateTarget += (s1, a1) =>
					{
						if(shouldUpdate)
							throw new InvalidOperationException("Stackoverflow !");
						shouldUpdate = true;
						a1.Content = "hehe";
					};
				}
			};
			repository.Initialize();
			Assert.IsTrue(shouldUpdate);
			Assert.IsTrue(File.Exists(generatedFileName));
		}

		[TestMethod]
		public void DeletingSourceShouldDeleteTarget()
		{
			var repository = new DirectoryCodeRepository(new MockCodeItemMementoRepository());
			var fileName = Helper.CreateFile("DeletingSourceShouldDeleteTarget");
			var generatedFileName = "DeletingSourceShouldDeleteTarget.Gen";
			repository.Files.Add(fileName);
			repository.CodeItemCreated += new CodeItemCreatedHandler(repository_CodeItemCreated);
			repository.Initialize();

			File.Delete(fileName);

			repository = new DirectoryCodeRepository(repository.MementoRepository);
			repository.CodeItemCreated += new CodeItemCreatedHandler(repository_CodeItemCreated);
			repository.Initialize();

			Assert.IsFalse(File.Exists(generatedFileName));
		}

		void repository_CodeItemCreated(ICodeRepository s, CodeItem a)
		{
			if(a.Name == "DeletingSourceShouldDeleteTarget")
			{
				var dep = a.SourceOf("DeletingSourceShouldDeleteTarget.Gen");
				dep.ShouldUpdateTarget += (s1, a1) =>
				{
					a1.Content = "hello";
				};
			}
		}


	}
}
